package aliyunsms.sms.controller;

import aliyunsms.sms.service.SMS;
import com.aliyuncs.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author lmx
 * @Date 2021/4/27 16:06
 * @Version 1.0
 */
@RestController
@CrossOrigin
public class SmsApiController {
    @Autowired
    private SMS sms ;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public String code(@PathVariable("phone") String phone){
        //调用发送方法redis
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)){
            return phone +":"+ code +"验证码已存在，还没有过期";//防止重复发送
        }

        //生成验证码存储
        code = UUID.randomUUID().toString().substring(0, 4);
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("code",code);


        boolean isSF = sms.send(phone, "", hashMap);

        if (isSF){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return phone+":"+code+" 发送成功";
        }else{
            return phone+":"+code+" 发送失败";
        }

    }
}
